package com.huanzhidadi.jsoup;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

public class DownloadImgDemo {
    public static void main(String[] args) throws IOException {
        Document document = Jsoup.parse(new URL("https://mp.weixin.qq.com/s/qeClNY3mmMTwEBSfahGsyg"), 10000);
        Elements title = document.getElementsByClass("rich_media_title");

        Element content = document.getElementById("js_content");
        Elements imgs = content.getElementsByTag("img");
        for (int i=0; i< imgs.size(); i++) {
            Element img = imgs.get(i);
            String url = img.attr("data-src");
            System.out.println(url);
            generateImg(url, title.text()+"_"+i);
        }

    }

    private static void generateImg(String url, Object name) throws IOException {
        URL target = new URL(url);
        URLConnection urlConnection = target.openConnection();
        InputStream inputStream = urlConnection.getInputStream();
        FileOutputStream outputStream = new FileOutputStream("D:\\IdeaProjects\\java-interview-collect\\jsoup\\src\\main\\resources\\imgs\\"
                + name + ".jpg");

        int temp = 0;
        while ((temp=inputStream.read()) != -1) {
            outputStream.write(temp);
        }
        System.out.println(name + ".jpg下载完毕！");
    }
}
